
import {useRecoilValue} from 'recoil'
import {getLoginInfoState} from '@selectors/selectLoginInfo'

const LoginInfo = useRecoilValue(getLoginInfoState)

const headersTokenConfig = {
  headers: {
    Accept: "application/json",
    "content-type": "application/json; charset=utf-8",
    Authorization: LoginInfo.userToken,
  },
};
const headersConfig = {
  headers: {
    Accept: "application/json",
    "content-type": "application/json; charset=utf-8",
  },
};
const httpRequest = new Proxy(window.fetch, {
  apply: <T extends any>(target:any, _obj:T, args:T) => {
    const default_header = LoginInfo.userToken
      ? headersTokenConfig
      : headersConfig;
    args[1] = { ...args[1], ...default_header };
    return target.apply(null, args);
  },
  // 拦截fetch的apply即调用行为，并统一加请求头
});

export const fetchRequest = (url: string, obj: Object = {}): Promise<void> => {
  return new Promise((resolve, reject) => {
    httpRequest(url, obj)
      .then((s:Response) => s.json())
      .then((result:any) => {
        resolve(result);
      })
      .catch((err:any) => {
        reject(err);
      });
  });
};
